package com.ykl.cas.controller;

import com.alibaba.fastjson.JSONObject;
import com.ykl.cas.utils.CheckUrlUtils;
import org.apereo.cas.services.RegexRegisteredService;
import org.apereo.cas.services.RegisteredService;
import org.apereo.cas.services.ReturnAllAttributeReleasePolicy;
import org.apereo.cas.services.ServicesManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.net.URL;
import java.util.Collection;
import java.util.HashMap;
//这个controller已经弃用
//@CrossOrigin
//@RestController
//@RequestMapping("/services")
public class ServicesManagerController {

  @Autowired
  @Qualifier("servicesManager")
  private ServicesManager servicesManager;

  //得到全部的service
  @PostMapping("getAllService")
  public Collection<RegisteredService> getAllService() {
    Collection<RegisteredService> allService = servicesManager.getAllServices();
    return allService;
  }

  //得到指定的service通过id
  @PostMapping("getServiceById")
  public String getServiceById(long id) {
    RegisteredService svc = servicesManager.findServiceBy(id);
    String svgStr = JSONObject.toJSONString(svc);
    return svgStr;
  }

  /**
   * 添加cas客户端
   * 增加了单点退出功能，cas退出默认使用隐式退出
   * protocol 代表的是协议，比如: http或者https的协议
   */
  @RequestMapping(value = "/addClient", method = RequestMethod.POST)
  public HashMap<Object, Object> addService(@RequestBody String regexregisteredservice) throws IOException {
    //json字符串转化成java对象
    HashMap map = JSONObject.parseObject(regexregisteredservice, HashMap.class);
    String url = map.get("sysUrl").toString();
    HashMap<Object, Object> data = new HashMap<>();
    boolean isUrl = CheckUrlUtils.isURL(url);
    if (!isUrl) {
      data.put("msg", "url格式不正确");
      data.put("code", 500);
      return data;
    }
    RegisteredService svc = servicesManager.findServiceBy(url);
    if (svc != null) {
      data.put("msg", "这个url已存在");
      data.put("code", 500);
      return data;
    }
    //serviceId,可以配置为正则匹配
    String a = "^" + url + ".*";
    RegexRegisteredService service = new RegexRegisteredService();
    ReturnAllAttributeReleasePolicy re = new ReturnAllAttributeReleasePolicy();
    service.setServiceId(a);
    service.setAttributeReleasePolicy(re);
    service.setName(map.get("name").toString());
    service.setLogo(map.get("logoUrl").toString());
    service.setDescription(map.get("description").toString());
    //单点登出
    service.setLogoutUrl(new URL(url));
    RegisteredService registeredService = servicesManager.save(service, true);
    if (registeredService != null) {
      servicesManager.load();
      data.put("msg", "添加成功");
      data.put("code", 200);
      data.put("RegisteredServiceList", servicesManager.load());
    }
    return data;
  }

  @PostMapping("/load")
  public Collection<RegisteredService> load(){
    return servicesManager.load();
  }
  /**
   * 删除服务,通过serviceId
   *
   * @param serviceId
   * @return
   */
  @RequestMapping(value = "/deleteByServiceId/{serviceId}", method = RequestMethod.GET)
  public String delServiceByServiceId(@PathVariable("serviceId") String serviceId) {
    String res = "";
    RegisteredService svc = servicesManager.findServiceBy(serviceId);
    if (svc != null) {
      try {
        servicesManager.delete(svc);
      } catch (Exception e) {
        if (null == servicesManager.findServiceBy(serviceId)) {
          res = "success";
          servicesManager.load();
        } else {
          res = "failed";
        }
      }
    }
    return res;
  }

  /**
   * 删除服务，通过id
   *
   * @param id
   * @return
   */
  @GetMapping("/deleteById/{id}")
  public String delServiceById(@PathVariable("id") long id) {
    System.out.println("********************delService-serviceId:" + id);
    String res = "";
    RegisteredService svc = servicesManager.findServiceBy(id);
    if (svc != null) {
      try {
        servicesManager.delete(svc);
      } catch (Exception e) {
        if (null == servicesManager.findServiceBy(id)) {
          res = "success";
          servicesManager.load();
        } else {
          res = "failed";
        }
      }
    }
    return res;
  }
}
